#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "TCPUtils.h"
#include "clientTask.h"

// 定义当前客户端支持的任务表
static ClientTask support_task[] = {
	{
		.command = "get",
		.handler = clientDownTask,
		.flags = 1,
	}, {
		.command = "put",
		.handler = clientUploadTask,
		.flags = 1,
	}, {
		.command = "list",
		.handler = clientListTask,
		.flags = 0,
	}, {
		.command = "help",
		.handler = clientShowHelp,
		.flags = 0,
	}
};
// 查找客户端支持的任务表，执行相应的处理函数
// parseInputStr(buf, argv[1], port);
// get a.txt
//     |
// help
//     |
void parseInputStr(const char *command, const char *hostname, unsigned short port) {
	TCPInfo *task = NULL;
	int i;

	for (i = 0; i < sizeof(support_task) / sizeof(support_task[0]); ++i) {
		if (strncasecmp(command, support_task[i].command,
						strlen(support_task[i].command)) == 0) {
			// 用户输入的字符串前面的单词是命令，解析后，跳过输入格式头
			command += strlen(support_task[i].command);
			break;
		}
	}
	if (i >= sizeof(support_task) / sizeof(support_task[0])) {
		fprintf(stderr, "system not support command!\n");
		return;
	}
	// 构造任务信息
	if (support_task[i].flags) {
		if (command[0] != ' ') {
			fprintf(stderr, "command format error, try again!\n");
			return;
		}
		task = createTCPInfo(hostname, port, command + 1);
	} else {
		task = createTCPInfo(hostname, port, NULL);
	}
    // TCPinfo  ip port filename
	support_task[i].handler(task);
	releaseTCPInfo(task);
}

/**
 * ./client     server_ip   server_port
 * @param argc
 * @param argv
 * @return
 */
int main(int argc, char *argv[]) {
	char buf[128];
	if (argc != 3) {
		fprintf(stderr, "usage: client ip port!\n");
		return -1;
	}

    // ./client server_ip server_port
    // ./client 192.168.254.1 7777
	char *endpoint;					// 存储转换结束的空间地址
	uint16_t port = (unsigned short )strtol(argv[2], &endpoint, 10);
	if (*endpoint != '\0') {		// 正常全部转换后，指向字符串空间的0位置
		fprintf(stderr, "convert failed!\n");
		return -1;
	}

	printf("<client>: ");
	fgets(buf, sizeof(buf), stdin);
	buf[strlen(buf) - 1] = 0;
	while (strcasecmp(buf, "quit") != 0) {
		parseInputStr(buf, argv[1], port);
		printf("<client>: ");
		fgets(buf, sizeof(buf), stdin);
		buf[strlen(buf) - 1] = 0;
	}
	return 0;
}
